package com.example.sys.dingtalk.service;

import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.example.core.utils.StringUtils;
import com.example.sys.dingtalk.constant.DingTalkConstant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class DingTalkTokenServiceImpl implements DingTalkTokenService {

    @Value("${ding.appKey}")
    private String appKey;

    @Value("${ding.appSecret}")
    private String appSecret;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public String getTokenByApi() throws Exception {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
        OapiGettokenRequest request = new OapiGettokenRequest();
        request.setAppkey(appKey);
        request.setAppsecret(appSecret);
        request.setHttpMethod("GET");
        OapiGettokenResponse response = client.execute(request);
        if (response != null && StringUtils.isNotEmpty(response.getBody())) {
            JSONObject body = JSONObject.parseObject(response.getBody());
            if (body.containsKey(DingTalkConstant.ACCESS_TOKEN) && body.containsKey(DingTalkConstant.EXPIRES_IN)) {
                Long expiresIn = body.getLong(DingTalkConstant.EXPIRES_IN);
                String token = body.getString(DingTalkConstant.ACCESS_TOKEN);
                redisTemplate.opsForValue().set(DING_TALK_TOKEN, token, expiresIn, TimeUnit.SECONDS);
                return token;
            }
        }
        throw new Exception("dingTalk access token get error ");
    }

    @Override
    public String getToken() throws Exception {
        Object token = redisTemplate.opsForValue().get(DING_TALK_TOKEN);
        if (token == null){
            return getTokenByApi();
        }
        return (String) token;
    }
}
